//! Decode a url encoded string
//! Performs error handling and returns a string
//! Call url_decoder.crack to use. It returns option<String> and check with
//! `result.is_some()` to see if it returned okay.

use crate::checkers::CheckerTypes;
use crate::decoders::interface::check_string_success;

use super::crack_results::CrackResult;
use super::interface::Crack;
use super::interface::Decoder;

use log::{debug, info, trace};

/// The url decoder, call:
/// `let url_decoder = Decoder::<URLDecoder>::new()` to create a new instance
/// And then call:
/// `result = url_decoder.crack(input)` to decode a url string
/// The struct generated by new() comes from interface.rs
/// ```
/// use ciphey::decoders::url_decoder::{URLDecoder};
/// use ciphey::decoders::interface::{Crack, Decoder};
/// use ciphey::checkers::{athena::Athena, CheckerTypes, checker_type::{Check, Checker}};
///
/// let decode_url = Decoder::<URLDecoder>::new();
/// let athena_checker = Checker::<Athena>::new();
/// let checker = CheckerTypes::CheckAthena(athena_checker);
///
/// let result = decode_url.crack("This%20is%20an%20example%20of%20a%20URL%20encoded%20string%20%3C%3E%3F%3D%7B%7D%7C", &checker).unencrypted_text;
/// assert!(result.is_some());
/// assert_eq!(result.unwrap()[0], "This is an example of a URL encoded string <>?={}|");
/// ```
pub struct URLDecoder;

impl Crack for Decoder<URLDecoder> {
    fn new() -> Decoder<URLDecoder> {
        Decoder {
            name: "URL",
            description: "URL encoding, officially known as percent-encoding, is a method to encode arbitrary data in a Uniform Resource Identifier (URI) using only the limited US-ASCII characters legal within a URI.",
            link: "https://en.wikipedia.org/wiki/URL_encoding",
            tags: vec!["url", "web", "decoder", "base"],
            popularity: 0.6,
            phantom: std::marker::PhantomData,
        }
    }

    /// This function does the actual decoding
    /// It returns an Option<string> if it was successful
    /// Else the Option returns nothing and the error is logged in Trace
    fn crack(&self, text: &str, checker: &CheckerTypes) -> CrackResult {
        trace!("Trying url with text {:?}", text);
        let decoded_text: Option<String> = decode_url_no_error_handling(text);

        trace!("Decoded text for url: {:?}", decoded_text);
        let mut results = CrackResult::new(self, text.to_string());

        if decoded_text.is_none() {
            debug!("Failed to decode url because URLDecoder::decode_url_no_error_handling returned None");
            return results;
        }

        let decoded_text = decoded_text.unwrap();
        if !check_string_success(&decoded_text, text) {
            info!(
                "Failed to decode url because check_string_success returned false on string {}",
                decoded_text
            );
            return results;
        }

        let checker_result = checker.check(&decoded_text);
        results.unencrypted_text = Some(vec![decoded_text]);

        results.update_checker(&checker_result);

        results
    }
    /// Gets all tags for this decoder
    fn get_tags(&self) -> &Vec<&str> {
        &self.tags
    }
    /// Gets the name for the current decoder
    fn get_name(&self) -> &str {
        self.name
    }
    /// Gets the description for the current decoder
    fn get_description(&self) -> &str {
        self.description
    }
    /// Gets the link for the current decoder
    fn get_link(&self) -> &str {
        self.link
    }
}

/// helper function
fn decode_url_no_error_handling(text: &str) -> Option<String> {
    // Runs the code to decode url
    // Doesn't perform error handling, call from_url
    if let Ok(decoded_text) = urlencoding::decode(text) {
        return Some(decoded_text.into_owned());
    }
    None
}

#[cfg(test)]
mod tests {
    use super::URLDecoder;
    use crate::{
        checkers::{
            athena::Athena,
            checker_type::{Check, Checker},
            CheckerTypes,
        },
        decoders::interface::{Crack, Decoder},
    };

    // helper for tests
    fn get_athena_checker() -> CheckerTypes {
        let athena_checker = Checker::<Athena>::new();
        CheckerTypes::CheckAthena(athena_checker)
    }

    #[test]
    fn url_decodes_successfully() {
        // This tests if URL can decode URL successfully
        let url_decoder = Decoder::<URLDecoder>::new();
        let result = url_decoder.crack(
            "This%20is%20an%20example%20of%20a%20URL%20encoded%20string%20%3C%3E%3F%3D%7B%7D%7C",
            &get_athena_checker(),
        );
        assert_eq!(
            result.unencrypted_text.unwrap()[0],
            "This is an example of a URL encoded string <>?={}|"
        );
    }

    #[test]
    fn url_handles_panics() {
        // This tests if URL can handle panics
        // It should return None
        let url_decoder = Decoder::<URLDecoder>::new();
        let result = url_decoder
            .crack(
                "hello my name is panicky mc panic face!",
                &get_athena_checker(),
            )
            .unencrypted_text;
        assert!(result.is_none());
    }

    #[test]
    fn url_handles_panic_if_empty_string() {
        // This tests if URL can handle an empty string
        // It should return None
        let url_decoder = Decoder::<URLDecoder>::new();
        let result = url_decoder
            .crack("", &get_athena_checker())
            .unencrypted_text;
        assert!(result.is_none());
    }

    #[test]
    fn url_handles_panic_if_emoji() {
        // This tests if URL can handle an emoji
        // It should return None
        let url_decoder = Decoder::<URLDecoder>::new();
        let result = url_decoder
            .crack("😂", &get_athena_checker())
            .unencrypted_text;
        assert!(result.is_none());
    }
}
